const path = require('path');
const {exec} = require('child_process');
const fs = require('fs');
const https = require('https');

// APK文件路径
const bundlePath = path.resolve(
  __dirname,
  './android/app/build/outputs/apk/release/app-arm64-v8a-release.apk',
);

// 远程服务器配置
const REMOTE_SERVER = 'root@114.55.0.234';
const REMOTE_PATH = '/usr/local/tsun/web/tsc/private';
const APK_NAME = 'app-release.apk';

// 企业微信Webhook配置
const WEBHOOK_URL =
  'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=58b353de-325a-4ee5-9f32-0aee84f94a12';

// Loading动画类
class TerminalLoader {
  constructor() {
    this.frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
    this.colors = {
      reset: '\x1b[0m',
      bright: '\x1b[1m',
      red: '\x1b[31m',
      green: '\x1b[32m',
      yellow: '\x1b[33m',
      blue: '\x1b[34m',
      magenta: '\x1b[35m',
      cyan: '\x1b[36m',
    };
    this.currentFrame = 0;
    this.interval = null;
    this.message = '';
  }

  start(message) {
    this.message = message;
    this.currentFrame = 0;

    // 隐藏光标
    process.stdout.write('\x1B[?25l');

    this.interval = setInterval(() => {
      const frame = this.frames[this.currentFrame];
      process.stdout.write(
        `\r${this.colors.cyan}${frame}${this.colors.reset} ${this.colors.bright}${this.message}${this.colors.reset}`,
      );
      this.currentFrame = (this.currentFrame + 1) % this.frames.length;
    }, 100);
  }

  success(message) {
    this.stop();
    console.log(`${this.colors.green}✅ ${message}${this.colors.reset}`);
  }

  error(message) {
    this.stop();
    console.log(`${this.colors.red}❌ ${message}${this.colors.reset}`);
  }

  warning(message) {
    this.stop();
    console.log(`${this.colors.yellow}⚠️  ${message}${this.colors.reset}`);
  }

  info(message) {
    this.stop();
    console.log(`${this.colors.blue}ℹ️  ${message}${this.colors.reset}`);
  }

  stop() {
    if (this.interval) {
      clearInterval(this.interval);
      this.interval = null;
      process.stdout.write('\r\x1b[K'); // 清除当前行
      // 显示光标
      process.stdout.write('\x1B[?25h');
    }
  }
}

// 进度条类
class ProgressBar {
  constructor(total = 100) {
    this.total = total;
    this.current = 0;
    this.colors = {
      reset: '\x1b[0m',
      green: '\x1b[32m',
      blue: '\x1b[34m',
      bright: '\x1b[1m',
    };
  }

  update(current, message = '') {
    this.current = current;
    const percentage = Math.floor((current / this.total) * 100);
    const filled = Math.floor((current / this.total) * 30);
    const empty = 30 - filled;

    const bar = '█'.repeat(filled) + '░'.repeat(empty);
    const display = `${this.colors.blue}[${this.colors.green}${bar}${this.colors.blue}] ${this.colors.bright}${percentage}%${this.colors.reset} ${message}`;

    process.stdout.write(`\r${display}`);

    if (current >= this.total) {
      console.log(''); // 换行
    }
  }
}

// 发送企业微信Webhook通知
function sendWebhookNotification(message) {
  return new Promise((resolve, reject) => {
    const loader = new TerminalLoader();
    loader.start('发送通知消息...');

    const data = JSON.stringify({
      msgtype: 'text',
      text: {
        content: message,
        mentioned_mobile_list: ['17805245629', '16668085001'],
      },
    });

    const url = new URL(WEBHOOK_URL);
    const options = {
      hostname: url.hostname,
      port: 443,
      path: url.pathname + url.search,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(data),
      },
    };

    const req = https.request(options, res => {
      let responseData = '';

      res.on('data', chunk => {
        responseData += chunk;
      });

      res.on('end', () => {
        if (res.statusCode === 200) {
          loader.success('通知消息发送成功');
          resolve(responseData);
        } else {
          loader.error(`通知消息发送失败: HTTP ${res.statusCode}`);
          reject(new Error(`HTTP ${res.statusCode}: ${responseData}`));
        }
      });
    });

    req.on('error', error => {
      loader.error(`通知消息发送失败: ${error.message}`);
      reject(error);
    });

    req.write(data);
    req.end();
  });
}

// 执行命令的Promise包装函数（带loading）
function executeCommand(command, description) {
  return new Promise((resolve, reject) => {
    const loader = new TerminalLoader();

    console.log(
      `\n${loader.colors.magenta}🚀 准备执行: ${description}${loader.colors.reset}`,
    );
    console.log(`${loader.colors.blue}命令: ${command}${loader.colors.reset}`);

    loader.start(`正在${description}...`);

    exec(command, (error, stdout, stderr) => {
      if (error) {
        loader.error(`${description} 失败: ${error.message}`);
        reject(error);
        return;
      }

      if (stderr) {
        loader.warning(`${description} 警告: ${stderr}`);
      }

      loader.success(`${description} 完成`);

      if (stdout) {
        console.log(
          `${loader.colors.blue}输出:${loader.colors.reset}\n${stdout}`,
        );
      }

      resolve(stdout);
    });
  });
}

// 检查文件是否存在（带loading）
function checkFileExists(filePath) {
  const loader = new TerminalLoader();

  loader.start('检查APK文件...');

  // 模拟检查延迟
  setTimeout(() => {
    if (!fs.existsSync(filePath)) {
      loader.error(`APK文件不存在: ${filePath}`);
      throw new Error(`APK文件不存在: ${filePath}`);
    }
    loader.success(`找到APK文件: ${filePath}`);
  }, 500);
}

// 主发布流程（带进度条）
async function releaseAndroid() {
  const loader = new TerminalLoader();
  const progressBar = new ProgressBar(7);

  try {
    console.log(
      `${loader.colors.cyan}═══════════════════════════════════════════════════════════${loader.colors.reset}`,
    );
    console.log(
      `${loader.colors.bright}${loader.colors.magenta}      🎯 Android应用发布系统 v1.0      ${loader.colors.reset}`,
    );
    console.log(
      `${loader.colors.cyan}═══════════════════════════════════════════════════════════${loader.colors.reset}\n`,
    );

    progressBar.update(0, 'apk构建中...');
    const pingCommand = 'cd ./android && ./gradlew assembleRelease && cd ..';
    await executeCommand(pingCommand, '构建apk');

    // 步骤1: 检查APK文件
    progressBar.update(1, '检查APK文件...');
    checkFileExists(bundlePath);
    await new Promise(resolve => setTimeout(resolve, 600)); // 等待检查完成

    // 步骤2: 上传APK
    progressBar.update(2, '上传APK文件...');
    const scpCommand = `scp ${bundlePath} ${REMOTE_SERVER}:${REMOTE_PATH}/`;
    await executeCommand(scpCommand, '上传APK文件到远程服务器');

    // 步骤3: 修改权限
    progressBar.update(3, '修改文件权限...');
    const chownCommand = `ssh ${REMOTE_SERVER} "chown nginx:nginx ${REMOTE_PATH}/${APK_NAME}"`;
    await executeCommand(chownCommand, '修改远程服务器文件权限');

    // 步骤4: 验证部署
    progressBar.update(4, '验证部署结果...');
    const verifyCommand = `ssh ${REMOTE_SERVER} "ls -la ${REMOTE_PATH}/${APK_NAME}"`;
    await executeCommand(verifyCommand, '验证文件上传状态');

    // 步骤5: 获取Git提交日志
    progressBar.update(5, '获取Git提交日志...');
    let gitLogInfo = '';
    try {
      const gitLogCommand = 'git log --oneline origin/$(git rev-parse --abbrev-ref HEAD)..HEAD';
      const gitLogOutput = await executeCommand(gitLogCommand, '获取最新提交日志');
      if (gitLogOutput.trim()) {
        gitLogInfo = `\n📝 最新提交:\n${gitLogOutput.trim()}`;
      }
    } catch (gitError) {
      console.log(`${loader.colors.yellow}⚠️  无法获取Git日志: ${gitError.message}${loader.colors.reset}`);
    }

    // 步骤6: 发送通知
    progressBar.update(6, '发送通知消息...');
    const notificationMessage = `🎉 Android应用发布完成！\n📱 APK已成功部署到: ${REMOTE_SERVER}:${REMOTE_PATH}/${APK_NAME}\n⏰ 发布时间: ${new Date().toLocaleString(
      'zh-CN',
    )}\n📥 下载地址: https://monitoring.tsun-ess.cn/private/app-release.apk${gitLogInfo}`;
    await sendWebhookNotification(notificationMessage);

    // 步骤7: 推送到远端
    progressBar.update(7, '推送到远端仓库...');
    try {
      const gitPushCommand = 'git push';
      await executeCommand(gitPushCommand, '推送代码到远端仓库');
    } catch (gitPushError) {
      console.log(`${loader.colors.yellow}⚠️  Git推送失败: ${gitPushError.message}${loader.colors.reset}`);
      console.log(`${loader.colors.yellow}   发布仍然成功，但代码未推送到远端${loader.colors.reset}`);
    }

    console.log(
      `\n${loader.colors.green}${loader.colors.bright}🎉 恭喜！Android应用发布完成！${loader.colors.reset}`,
    );
    console.log(
      `${loader.colors.cyan}📱 APK已成功部署到: ${loader.colors.yellow}${REMOTE_SERVER}:${REMOTE_PATH}/${APK_NAME}${loader.colors.reset}`,
    );
    console.log(
      `${loader.colors.cyan}📥 下载地址: ${loader.colors.yellow}https://monitoring.tsun-ess.cn/private/app-release.apk${loader.colors.reset}`,
    );
    console.log(
      `${loader.colors.green}📢 通知消息已发送到企业微信群${loader.colors.reset}`,
    );
    console.log(
      `${loader.colors.green}🚀 代码已推送到远端仓库${loader.colors.reset}`,
    );
    console.log(
      `${loader.colors.cyan}═══════════════════════════════════════════════════════════${loader.colors.reset}\n`,
    );
  } catch (error) {
    loader.error(`发布失败: ${error.message}`);
    console.log(
      `${loader.colors.red}💥 发布过程中出现错误，请检查网络连接和服务器配置${loader.colors.reset}\n`,
    );
    process.exit(1);
  }
}

releaseAndroid();
